/* gcc -lrt */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <mqueue.h>

#include "msg.h"

int main(int argc, char *argv[])
{
    char pathname[80], cmd_str[80];
    struct stat fileattr;
    mqd_t fd, shmsize, ret;
    pid_t childpid1, childpid2;

    if(argc < 2) {
        printf("Usage: ./a.out filename\n");
        return EXIT_FAILURE;
    }

    fd = mq_open(argv[1], O_CREAT|O_WRONLY, 0666 , NULL); 
    /* /dev/mqeueue/filename as the message queue, creating if not exist */
    if(fd == -1) {
        ERR_EXIT("con: mq_open()");
    } 
    system("ls -l /dev/mqueue");
  
 

    char *argv1[] = {" ", argv[1], 0};
    childpid1 = vfork();
    if(childpid1 < 0) {
        ERR_EXIT("msgcon: 1st vfork()");
    } 
    else if(childpid1 == 0) {
        execv("./msgproducer.o", argv1); /* call msgproducer with filename */
    }
    else {
        childpid2 = vfork();
        if(childpid2 < 0) {
            ERR_EXIT("msgcon: 2nd vfork()");
        }
        else if (childpid2 == 0) {
            execv("./msgconsumer.o", argv1); /* call msgconsumer with filename */
        }
        else {
            wait(&childpid1);
            wait(&childpid2);
            //关闭
            mq_close(fd);

            //释放连接
            mq_unlink(argv[1]);
            system("ls -l /dev/mqueue/");  
        }
    }
    exit(EXIT_SUCCESS);
}

